extends Area2D

signal hurt
signal died

@export var speed := 150
@export var cooldown := 0.25
@export var bullet_scene:PackedScene
var can_shoot = true

var health := 100

@onready var screensize = get_viewport_rect().size
@onready var ship: Sprite2D = $Ship
@onready var boosters: AnimatedSprite2D = $Ship/Boosters
@onready var gun_cooldown: Timer = $GunCooldown
@onready var animation_player: AnimationPlayer = $AnimationPlayer

func start()->void:
	position = Vector2(screensize.x/2,screensize.y-64)
	gun_cooldown.wait_time = cooldown
	
	
func shoot():
	if not can_shoot:
		return
	can_shoot = false
	gun_cooldown.start()
	var b = bullet_scene.instantiate()
	get_tree().root.add_child(b)
	b.start(position+Vector2(0,-8))

func _ready() -> void:
	start()

func _process(delta: float) -> void:
	var input = Input.get_vector("left","right","up","down")
	if input.x > 0:
		ship.frame = 2
		boosters.animation = "right"
	elif input.x < 0:
		ship.frame = 0
		boosters.animation = "left"
	else:
		ship.frame = 1
		boosters.animation = "forward"
	position += input * speed * delta
	position = position.clamp(Vector2(10,10),screensize-Vector2(10,10))
	
	#射击
	if Input.is_action_pressed("shoot"):
		shoot()

#计时器到时回调 到时后设置射击标志为可射击
func _on_gun_cooldown_timeout() -> void:
	can_shoot = true 


func _on_area_entered(area: Area2D) -> void:
	if area.is_in_group("enemies"):
		health = clampi(health-20,0,100)
		hurt.emit(health)
		area.explode()
		
	if area.is_in_group("enemy_bullets"):
		#print("enter.,..",area.name)
		#计算血量
		health = clampi(health-10,0,100)
		hurt.emit(health)
		area.destroy()
	
	#print("current health:",health)
		
	if health == 0:
		animation_player.play("destroy")
		boosters.visible = false
		await animation_player.animation_finished
		died.emit()
		queue_free()
